package com.ld.hpfs.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ld.hpfs.dao.SplitAndMergeMapper;
import com.ld.hpfs.pojo.IdDetail;
import com.ld.hpfs.pojo.Invoice;
import com.ld.hpfs.pojo.TaxSystemParameter;

/**
 * <pre>
 * 单据操作 功能// 
 * @author Eric
 *</pre>
 */
@Service
public class InvoiceFunctionUtil {
	@Autowired
	private SplitAndMergeMapper splitAndMergeMapper;

	
	public Integer[] getIntegerByString(String id[]) {
		Integer[] ids = new Integer[id.length];
		for (int i = 0; i < id.length; i++) {
			ids[i] = Integer.parseInt(id[i]);
		}
		return ids;
	}

	/**
	 * 泡泡排序 冒泡
	 * 
	 * @param list
	 * @return
	 */
	public List<IdDetail> sortMaxAmountIdDetail(List<IdDetail> list) {
		List<IdDetail> listMaxMin = new ArrayList<IdDetail>();

		double[] amount = this.getAmountCru(list);
//		List<IdDetail> listMaxMinww = new ArrayList<IdDetail>();
//		listMaxMinww.addAll(list);
		for (int j = 0; j < amount.length; j++) {
			//System.out.println("第j"+j+"个amount,shi="+amount[j]);
			for (int i = 0; i < list.size(); i++) {
				IdDetail vo1 = list.get(i);
				if (DoubleUtil.isSame(vo1.getAmount_cur(),amount[j])) {
				//	System.out.println("第j"+j+"个amount,shi="+amount[j]+"       vo的amount为=i "+i+"=="+vo1.getAmountCur());
//					if(listMaxMinww.contains(vo1)){
						list.remove(i);
//    					listMaxMinww.remove(vo1);
    					listMaxMin.add(vo1);
//    					System.out.println("list的个数是="+list.size() +"     list remove 的 vo amount="+vo1.getAmountCur());
//    					System.out.println("listMaxMin的个数是="+listMaxMin.size() +"     listMaxMin add 的 vo amount="+vo1.getAmountCur());
//    					System.out.println();
					break;
//					}
				}
			}
		}
//		listMaxMin.addAll(listMaxMinww);
		//please validate
//		List<IdDetail> listMaxMinww = new ArrayList<IdDetail>();
//		listMaxMinww.addAll(listMaxMin);
//		double sumAmount=0;
//		for (int j = 0; j < amount.length; j++) {
//			sumAmount+=amount[j];
//    		for (int i = 0; i < listMaxMinww.size(); i++) {
//    			IdDetail vo = listMaxMinww.get(i);
//    			sumAmount=DoubleUtil.sub(sumAmount, vo.getAmountCur());
//    			listMaxMinww.remove(i);
//    			break;
//    		}
//		}
//		if(sumAmount==0){
//			System.out.println("OOOOOOOOKKKKKKKKKKYES");
//		}else{
//			System.out.println("FAILE#########################");
//		}
//		
		return listMaxMin;
	}

	/**
	 * 泡泡排序 冒泡
	 * 
	 * @param list
	 * @return
	 */
	public List<IdDetail> sortMaxAmountIdDetailTT(List<IdDetail> list) {
		List<IdDetail> listMaxMin = new ArrayList<IdDetail>();
		double[] amount = this.getAmountCru(list);
		for (int j = 0; j < amount.length; j++) {
			for (int i = 0; i < list.size(); i++) {
				IdDetail vo1 = (IdDetail)list.get(i).clone();
				if (vo1.getAmount_cur() == amount[j]) {
					list.remove(vo1);
					listMaxMin.add(vo1);
					break;
				}
			}
		}
		return listMaxMin;
	}
	
	/**
	 * 泡泡 获取 金额
	 * @param list
	 * @return
	 */
	private double[] getAmountCru(List<IdDetail> list) {
		double[] amountD = new double[list.size()];
		for (int i = 0; i < list.size(); i++) {
			IdDetail vo = list.get(i);
			amountD[i] = vo.getAmount_cur();
		}
		// 从大到小
		double temp = 0;
		for (int j = 1; j <= amountD.length; j++) {
			for (int i = 0; i < amountD.length - 1; i++) {
				if (amountD[i] < amountD[i + 1]) {
					temp = amountD[i];
					amountD[i] = amountD[i + 1];
					amountD[i + 1] = temp;
				}
			}
		}
		return amountD;
	}
	/**
	 *	拆分明细单据信息
	 * @param list  明细集合
	 * @param tih   主单据信息
	 * @param maxAmount 	最大开票金额
	 * @return
	 * @throws Exception
	 */
	public List<IdDetail> splitIdDetail(List<IdDetail> list,Invoice tih,TaxSystemParameter taxSystemParameterPo,String idheadCode)throws Exception{
		//最大的明细	
		IdDetail idDetail=list.get(0);
		double amountMax= 0;
		
//		- price_way = 0 时，amount_cur - discount_sum 汇总到 amount_cur_total，tax_amount - discount_tax 汇总到tax_amount
//		- price_way = 1 时，amount_cur - discount_sum - tax_amount + discount_tax 汇总到 amount_cur_total，tax_amount - discount_tax 汇总到tax_amount

		if((int)idDetail.getPrice_way()==IdDetail.priceWay0){
			amountMax = DoubleUtil.sub(idDetail.getAmount_cur(), idDetail.getDiscount_sum());
		}else if((int)idDetail.getPrice_way()==IdDetail.priceWay1){
			amountMax =DoubleUtil.add(DoubleUtil.sub( DoubleUtil.sub( idDetail.getAmount_cur(),-idDetail.getDiscount_sum()),idDetail.getTax_amount()),idDetail.getDiscount_tax());
		}else{
			amountMax = DoubleUtil.sub(idDetail.getAmount_cur(),idDetail.getDiscount_sum());
		}
		List<IdDetail> listSplit=new ArrayList<IdDetail>();
		listSplit.add(idDetail);
		boolean isListOne=true;
		for (int i = list.size()-1; i>0;i--) {
			isListOne=false;
			IdDetail vo=list.get(i);
			if((int)vo.getPrice_way()==IdDetail.priceWay0){
				if((amountMax+(vo.getAmount_cur()-vo.getDiscount_sum()))<=taxSystemParameterPo.getMax_amount()){
					listSplit.add(vo);
					amountMax=DoubleUtil.add(amountMax,DoubleUtil.sub(vo.getAmount_cur()-vo.getDiscount_sum()));
					list.remove(i);
					isListOne=true;
				}else{
					list.remove(idDetail);
					break;
				}
			}else if((int)vo.getPrice_way()==IdDetail.priceWay1){
				if((amountMax+(vo.getAmount_cur()-vo.getDiscount_sum()-vo.getTax_amount()+vo.getDiscount_tax()))<=taxSystemParameterPo.getMax_amount()){
					listSplit.add(vo);
					amountMax= DoubleUtil.add(amountMax,DoubleUtil.add(DoubleUtil.sub( DoubleUtil.sub( vo.getAmount_cur(),-vo.getDiscount_sum()),vo.getTax_amount()),vo.getDiscount_tax()));
					list.remove(i);
					isListOne=true;
				}else{
					list.remove(idDetail);
					break;
				}
			}	
		}
		
		if(isListOne){
			if(list.contains(idDetail)){
				list.remove(idDetail);
			}
		}		
		
		this.saveIdHead(tih,amountMax, listSplit,idheadCode);
		return list;
	}
	/**
	 * @param maxMoney 
	 * @param listOriginal  初始化的明细列表
	 * @return              返回拆分后的符合拆分超过最大金额的明细
	 * @throws Exception
	 */
	public Object[] getMaxIdDetail(double maxMoney,List<IdDetail> listOriginal,TaxSystemParameter taxSystemParameterPo,boolean withTrialCalculation,String result,String curLan)throws Exception{
		List<IdDetail> listIdDetailAll=new ArrayList<IdDetail>();
		Object obj[]=new Object[2];
		double amountCurTotal = 0;
		boolean isWithTrialCalculation = false;
		for (int i = 0; i < listOriginal.size(); i++) {
			IdDetail idDetail=(IdDetail)listOriginal.get(i).clone();
			
			//用amount_cur - discount_sum 或 amount_cur - discount_sum - tax_amount + discount_tax 做是否超额校验 
			if((int)idDetail.getPrice_way()==IdDetail.priceWay0){
				amountCurTotal = idDetail.getAmount_cur()-idDetail.getDiscount_sum();
			}else if((int)idDetail.getPrice_way()==IdDetail.priceWay1){
				amountCurTotal = idDetail.getAmount_cur()-idDetail.getDiscount_sum()-idDetail.getTax_amount()+idDetail.getDiscount_tax();
			}
			
			if(amountCurTotal > maxMoney){
				List<IdDetail> listSplitDetail=this.getMaxAmountCount(idDetail, maxMoney,taxSystemParameterPo,withTrialCalculation,result);
				if(listSplitDetail.size()==0){
					//现在有尾差判断拆分
					if(withTrialCalculation){
						result="拆分的结果将会有尾差,是否允许有尾差拆分";	
					}else{
						listSplitDetail=this.getMaxAmountCount(idDetail, maxMoney,taxSystemParameterPo,false,result);
						isWithTrialCalculation = true;
					}
				}
				if(!withTrialCalculation){
		    		 result="";//CommonResources.getText(curLan, "tax.model.IdHead.IdHeadCode")+": "+idDetail.getIdHeadCode()+" 尾差金额:"+SplitTools.amountMiss+" 尾差税额:"+SplitTools.taxesMiss+" 尾差折扣金额:"+SplitTools.discountAmountMiss+" 尾差折扣税额:"+SplitTools.discountTaxesMiss;
		    		 isWithTrialCalculation = false;
				}
				listIdDetailAll.addAll(listSplitDetail);
			}else{
				listIdDetailAll.add(idDetail);
			}
//			listOriginal.remove(idDetail);
		}
		obj[0]=listIdDetailAll;
		obj[1]=result;
		return obj;
	}

	/**
	 * 得到拆分的数量
	 * @return
	 */
	private List<IdDetail> getMaxAmountCount(IdDetail idDetail,double maxMoney,TaxSystemParameter taxSystemParameterPo,boolean withTrialCalculation,String result)throws Exception{
		List<Double> listData=new ArrayList<Double>();
				
		//splitMethod 0  按数量
		//splitMethod 1  按单价
		double taxMiss = 0.0;
		if((idDetail.getSplitMethod()==null?(short)0:idDetail.getSplitMethod())==IdDetail.splitMethod0){
			SplitTools splitToos=new SplitTools(taxSystemParameterPo.getMax_amount(),false,0);
    		listData=splitToos.getSplitNumbers(idDetail.getDocument_no(),listData, taxSystemParameterPo.getSplit_precision(), taxSystemParameterPo.getSplit_step(), idDetail.getPrice_cur(),
    				idDetail.getQuantity(), idDetail.getTax_rate(),idDetail.getAmount_cur(),idDetail.getTax_amount(), idDetail.getDiscount_rate(),idDetail.getDiscount_sum(),(int)idDetail.getPrice_way(),withTrialCalculation);
    		taxMiss = splitToos.detailTaxesMissSum;
		}else if(idDetail.getSplitMethod()==IdDetail.splitMethod1){
			SplitTools splitToos=new SplitTools(taxSystemParameterPo.getMax_amount(),true,0);
			listData=splitToos.getSplitNumbers(idDetail.getDocument_no().toString(),listData, taxSystemParameterPo.getSplit_precision(), taxSystemParameterPo.getSplit_step(), idDetail.getPrice_cur(),
    				idDetail.getQuantity(), idDetail.getTax_rate(),idDetail.getAmount_cur(),idDetail.getTax_amount(), idDetail.getDiscount_rate(),idDetail.getDiscount_sum(),(int)idDetail.getPrice_way(),withTrialCalculation);
			taxMiss = splitToos.detailTaxesMissSum;
		}else{
			SplitTools splitToos=new SplitTools(taxSystemParameterPo.getMax_amount(),false,0);
			listData=splitToos.getSplitNumbers(idDetail.getDocument_no().toString(),listData, taxSystemParameterPo.getSplit_precision(), taxSystemParameterPo.getSplit_step(), idDetail.getPrice_cur(),
    				idDetail.getQuantity(), idDetail.getTax_rate(), idDetail.getAmount_cur(),idDetail.getTax_amount(), idDetail.getDiscount_rate(),idDetail.getDiscount_sum(),Integer.parseInt(String.valueOf(idDetail.getPrice_way())),withTrialCalculation);
			taxMiss = splitToos.detailTaxesMissSum;
		}
//		System.out.println("getDiscountTax="+idDetail.getDiscountTax());
//		System.out.println("getSplitPrecision="+taxSystemParameterPo.getSplitPrecision());
//		System.out.println("getSplitLength="+taxSystemParameterPo.getSplitLength());
//		System.out.println("getPriceCur="+idDetail.getPriceCur());
//		System.out.println("getQuantity="+idDetail.getQuantity());
//		System.out.println("getTaxRate="+idDetail.getTaxRate());
//		System.out.println("getAmountCur"+idDetail.getAmountCur());
//		System.out.println("getDiscountRate="+idDetail.getDiscountRate());
//		System.out.println("getDiscountSum="+idDetail.getDiscountSum());
//		System.out.println("getPriceWay="+Integer.parseInt(String.valueOf(idDetail.getPriceWay())));
//		System.out.println("getTaxAmount"+idDetail.getTaxAmount());
//		List<Double> listData2=new ArrayList<Double>();
//		listData2=splitToos2.getSplitNumbers(listData2,0.01      ,0.01   ,343521.0,1.0   ,0.17,343521.0,0.0,0.0,
//				Integer.parseInt(String.valueOf(0)),true);
		
		// price_way = 0 时，amount_cur - discount_sum 汇总到 amount_cur_total，tax_amount - discount_tax 汇总到tax_amount
	   // price_way = 1 时，amount_cur - discount_sum - tax_amount + discount_tax 汇总到 amount_cur_total，tax_amount - discount_tax 汇总到tax_amount	
//		折扣金额” = （未拆分前折扣金额/未拆分前金额）×拆分结果的金额，保留2位小数
//		System.out.println("splitMethod="+idDetail.getSplitMethod());
//		for (int i = 0; i < listData.size(); i++) {
//			System.out.println(listData.get(i));
//		}
		List<IdDetail> listCount=new ArrayList<IdDetail>();
		double idDetailAmountCur = 0;
		for (int i = 0; i <listData.size(); i++) {
			IdDetail idVo=(IdDetail) idDetail.clone();
			if((idDetail.getSplitMethod()==null?(short)0:idDetail.getSplitMethod())==IdDetail.splitMethod0){
			    idDetailAmountCur=DoubleUtil.formatDigitDecimal(DoubleUtil.mul(listData.get(i),idDetail.getPrice_cur()),2);
				idVo.setAmount_cur(idDetailAmountCur);
				idVo.setQuantity(listData.get(i));
			}else if(idDetail.getSplitMethod()==IdDetail.splitMethod1){
			    idDetailAmountCur=DoubleUtil.formatDigitDecimal(DoubleUtil.mul(listData.get(i),idDetail.getQuantity()),2);
				idVo.setAmount_cur(idDetailAmountCur);
				idVo.setPrice_cur(listData.get(i));
			}else{
			    idDetailAmountCur=DoubleUtil.formatDigitDecimal(DoubleUtil.mul(listData.get(i),idDetail.getPrice_cur()),2);
				idVo.setAmount_cur(idDetailAmountCur);
				idVo.setQuantity(listData.get(i));
			}
			//折扣处理 start
//			“折扣金额” = （未拆分前折扣金额/未拆分前金额）×拆分结果的金额，保留2位小数
//			double ddd = idDetail.getDiscountSum()/idDetail.getAmountCur()*idVo.getAmountCur();
//			
//			System.out.println("ddd="+ddd);
//			
			idVo.setDiscount_sum(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(DoubleUtil.div(idDetail.getDiscount_sum(),idDetail.getAmount_cur()),idVo.getAmount_cur()), 2));
//			若计价是0，不含税，“折扣税额” = 上一步计算的拆分结果折扣金额×税率，保留2位小数
//			若计价是1，含税，“折扣税额” = (上一步计算的拆分结果折扣金额/1+税率)*税率，保留2位小数
			if((int)idDetail.getPrice_way()==IdDetail.priceWay0){
				idVo.setTax_amount(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(idDetailAmountCur,idVo.getTax_rate()),2));
				idVo.setDiscount_tax(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(idVo.getDiscount_sum(),idVo.getTax_rate()),2));
			}else if((int)idDetail.getPrice_way()==IdDetail.priceWay1){
//				idVo.setTaxAmount(DoubleUtil.formatDigitDecimal(idDetailAmountCur/(1+idVo.getTaxRate())*idVo.getTaxRate(),2));
//				idVo.setDiscountTax(DoubleUtil.formatDigitDecimal((idVo.getDiscountSum()/(1+idVo.getTaxRate()))*idVo.getTaxRate(),2));
				idVo.setTax_amount(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(DoubleUtil.div(idDetailAmountCur,DoubleUtil.add(1.0, idVo.getTax_rate())), idVo.getTax_rate()),2));
				idVo.setDiscount_tax(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(DoubleUtil.div(idVo.getDiscount_sum(),DoubleUtil.add(1.0, idVo.getTax_rate())),idVo.getTax_rate()),2));
			}else{
				idVo.setTax_amount(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(idDetailAmountCur,idVo.getTax_rate()),2));
				idVo.setDiscount_tax(DoubleUtil.formatDigitDecimal(DoubleUtil.mul(idVo.getDiscount_sum(),idVo.getTax_rate()),2));
			}
			//折扣处理 end
			if (!DoubleUtil.isSame(taxMiss, DoubleUtil.ZERO)) {
				idVo.setTax_amount(DoubleUtil.sub(idVo.getTax_amount(), taxMiss));
				taxMiss = DoubleUtil.ZERO;
			}
			
			listCount.add(idVo);
		}		
//		double curAmount=idDetail.getAmountCur();	
//		double countIdDetail=Math.floor(maxMoney/idDetail.getPriceCur());
//		double idDetailAmountCur=countIdDetail*idDetail.getPriceCur();
//		while(curAmount>=idDetailAmountCur){
//			IdDetail idVo=(IdDetail) idDetail.clone();
//			curAmount=curAmount-idDetailAmountCur;
//			idVo.setAmountCur(idDetailAmountCur);
//			idVo.setQuantity(countIdDetail);
//			idVo.setTaxAmount(idDetailAmountCur*idVo.getTaxRate());
//			listCount.add(idVo);
//		}
//		if(curAmount>0){
//			IdDetail idVo=(IdDetail) idDetail.clone();
//			countIdDetail=DoubleUtil.div2(curAmount,idDetail.getPriceCur());
//			idVo.setAmountCur(curAmount);
//			idVo.setQuantity(countIdDetail);
//			idVo.setTaxAmount(curAmount*idVo.getTaxRate());
//			listCount.add(idVo);
//		}
		return listCount;
	}

	/**
	 * 保存拆分好的明细
	 * @param tih
	 * @param idDetail
	 * @param listSplit
	 * @throws Exception
	 */
	public void saveIdHead(Invoice tih,double amountMax, List<IdDetail> listSplit,String idheadCodeOriginal) throws Exception {
		//保存拆分的信息
		String idheadCode=this.getSplitAmountMaxCode(tih.getNum());
		this.saveIdHeadNew(tih, listSplit, idheadCodeOriginal, idheadCode);
	}
	
	
	/**
	 * 保存拆分好的明细
	 * @param tih
	 * @param idDetail
	 * @param listSplit
	 * @throws Exception
	 */
	public void saveIdHeadManualSplit(Invoice tih,double amountMax, List<IdDetail> listSplit,String idheadCodeOriginal) throws Exception {
		//保存拆分的信息
		String idheadCode=this.getSplitAmountHeadCode(tih.getHeadId().toString());
		this.saveIdHeadNew(tih, listSplit, idheadCodeOriginal, idheadCode);
	}


	/**
	 * @param tih
	 * @param amountMax
	 * @param listSplit
	 * @param idheadCodeOriginal
	 * @param idheadCode
	 * @throws Exception
	 */
	public void saveIdHeadNew(Invoice tih, List<IdDetail> listSplit, String idheadCodeOriginal,
			String idheadCode) throws Exception {
		tih.setNum(idheadCode);
		tih.setOrignal_doc_no(idheadCodeOriginal);
		tih.setTotalLine(listSplit.size());
//		int pkId = daoIdHead.SaveOrUpdateGetId(tih);
		splitAndMergeMapper.saveInvoice(tih);
		HashMap<String, Object> param =  new HashMap<String, Object>();
		param.put("companyId", tih.getCompanyId());
		param.put("newDocNo", idheadCode);
		param.put("docNo", idheadCodeOriginal);
		splitAndMergeMapper.insertRelationTable(param);
		Integer pkId = splitAndMergeMapper.getInvoiceHeadId(tih);
		tih.setHeadId(pkId);
//		System.out.println("idheadCode="+idheadCode);
//		System.out.println("idheadId="+pkId);
		//累积明细不含税额
		double idDetailAmount=0;
		//累积明细税额
		double idDetailTaxAmount=0;
		for (int i = 0; i < listSplit.size();i++) {
			IdDetail tid = (IdDetail)listSplit.get(i).clone();
			// 保存
			tid.setGoods_line(i + 1);
			tid.setHeadId(pkId);
//			tid.setIdHeadCode(tih.getNum());
			tid.setDocument_no(tih.getNum());
//			 price_way = 0 时，amount_cur - discount_sum 汇总到 amount_cur_total，tax_amount - discount_tax 汇总到tax_amount
//			 price_way = 1 时，amount_cur - discount_sum - tax_amount + discount_tax 汇总到 amount_cur_total，tax_amount - discount_tax 汇总到tax_amount
			if((int)tid.getPrice_way()==IdDetail.priceWay0){
				idDetailAmount = DoubleUtil.add(idDetailAmount,DoubleUtil.sub(tid.getAmount_cur(),tid.getDiscount_sum())) ;
				idDetailTaxAmount = DoubleUtil.add(idDetailTaxAmount,DoubleUtil.sub(tid.getTax_amount(),tid.getDiscount_tax()));
			}else if((int)tid.getPrice_way()==IdDetail.priceWay1){
				idDetailAmount = DoubleUtil.add(idDetailAmount, DoubleUtil.add(DoubleUtil.sub(DoubleUtil.sub(tid.getAmount_cur(),tid.getDiscount_sum()),tid.getTax_amount())), tid.getDiscount_tax());
				idDetailTaxAmount = DoubleUtil.add(idDetailTaxAmount,DoubleUtil.sub(tid.getTax_amount(), tid.getDiscount_tax()));
			}
			
//			idDetailTaxAmount+=tid.getTaxAmount()==null?0:tid.getTaxAmount();
			//格式化小数位
			tid.setTax_amount(DoubleUtil.formatDigitDecimal(String.valueOf(tid.getTax_amount())==""?0:tid.getTax_amount(),2));
			tid.setAmount_cur(DoubleUtil.formatDigitDecimal(String.valueOf(tid.getAmount_cur())==""?0:tid.getAmount_cur(),2));
//			System.out.println("id=SPEC :"+tid.getSpec());
			splitAndMergeMapper.saveIdDetail(tid);
		}
		tih.setTotalAmount((float)DoubleUtil.formatDigitDecimal(idDetailAmount,2));
		tih.setTotalTax((float)DoubleUtil.formatDigitDecimal(idDetailTaxAmount,2));
//		tih.setIsMerge(Invoice.UNMERGE);
//		tih.setIsSplit(Invoice.UNSPLIT);
//		tih.setCodeAfterMerge("");
//		daoIdHead.UpdateInvoice(tih);
		splitAndMergeMapper.updateInvoice(tih);
	}
	
	/**
	 * 手动拆分 得到 最大的headCode
	 * @param idHeadCode
	 * @return
	 * @throws Exception 
	 */
	public String getManualSpliHeadCode(String idHeadCode) throws Exception{
		idHeadCode=idHeadCode+Invoice.isMaxAmount;
//		String idMax=daoIdHead.getIdheadByIdHeadCode(idHeadCode);
		String idMax=this.getInvoiceIdMax(idHeadCode);
		if(idMax==null){
			idMax=idHeadCode+0;
		}else{
			int count=Integer.parseInt(idMax.substring(idMax.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length()))+1;
			idMax=idMax.substring(0,idMax.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length())+count;
		}
		return idMax;
	}
	/**
	 * @param idHeadCode
	 * @return
	 * @throws Exception 
	 */
	public String getSplitAmountHeadCode(String idHeadCode) throws Exception{
		if(!idHeadCode.contains(Invoice.isMaxAmount)){
			idHeadCode=idHeadCode+Invoice.isMaxAmount;
		}else{
			idHeadCode=idHeadCode.substring(0,idHeadCode.indexOf(Invoice.isMaxAmount));
		}
//		String idMax=daoIdHead.getIdheadByIdHeadCode(idHeadCode);
		String idMax=this.getInvoiceIdMax(idHeadCode);
		if(idMax==null){
			idMax=idHeadCode+0;
		}else{
			int count=Integer.parseInt(idMax.substring(idMax.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length()))+1;
			idMax=idMax.substring(0,idMax.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length())+count;
		}
		return idMax;
	}
	
	/**
	 * 拆分超额 headCode  以idMax是否为空，
	 * @param idHeadCode
	 * @return
	 * @throws Exception 
	 */
	public String getSplitAmountMaxCode(String idHeadCode) throws Exception{
//		String idMax=daoIdHead.getIdheadByIdHeadCode(idHeadCode);
		String idMax=this.getInvoiceIdMax(idHeadCode);
		if(idMax==null||"null".equals(idMax)){
			idMax=idHeadCode+1;
		}else{
			int count=Integer.parseInt(idMax.substring(idMax.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length()))+1;
			idMax=idMax.substring(0,idMax.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length())+count;
		}
		return idMax;
	}
	
	public String getInvoiceIdMax(String idHeadCode) throws Exception{
		List<Invoice> result=splitAndMergeMapper.getInvoiceByCode(idHeadCode);
		String idHeadCodeStr="";
		String idHeadStr="";
		int sValue=0;
		int rValue=0;
		if (result != null && result.size() > 0) {
			for (int i = 0; i < result.size(); i++) {
				idHeadStr=result.get(i).getNum();
				rValue=Integer.parseInt(idHeadStr.substring(idHeadStr.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length()));
				if(sValue<=rValue){
					sValue=rValue;
					idHeadCodeStr=result.get(i).getNum();
				}
			}
			return idHeadCodeStr;
		}
		return null;
	}
	
	/**
	 * 拆分超额 headCode  以result即daoIdHead.getIdheadCode(idHeadCode)
	 * @param idHeadCode
	 * @return
	 * @throws Exception 
	 */
	public String getSplitMaxCode(String idHeadCode) throws Exception{
//		List<Invoice> result = daoIdHead.getIdheadCode(idHeadCode);
		List<Invoice> result = splitAndMergeMapper.getInvoiceByCode(idHeadCode);
		String idHeadCodeStr = "";
		if(result!=null&&result.size()>0){
			int sValue=0;
			int rValue=0;
			if(result.size()==1){
				idHeadCodeStr = result.get(0).getHeadId()+Invoice.isMaxAmount+0;
			}else if(result.size()>1){
				for (int i = 0; i < result.size(); i++) {
				idHeadCodeStr = result.get(i).getHeadId().toString();
				if(idHeadCodeStr.contains(Invoice.isMaxAmount)){
				rValue=Integer.parseInt(idHeadCodeStr.substring(idHeadCodeStr.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length()));
	    			if(sValue<=rValue){
	    				sValue=rValue;
	    				idHeadCodeStr=result.get(i).getHeadId().toString();
	    			}
				}
				}
				int count=Integer.parseInt(idHeadCodeStr.substring(idHeadCodeStr.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length()))+1;
				idHeadCodeStr=idHeadCodeStr.substring(0,idHeadCodeStr.lastIndexOf(Invoice.isMaxAmount)+Invoice.isMaxAmount.length())+count;
			}
		}
		return idHeadCodeStr;
	}
}
